<template>
  <div class="form-container">
    <div class="form-top"></div>
    <div class="form-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/appCateList' }"
          >APP首页分类</el-breadcrumb-item
        >
        <el-breadcrumb-item>编辑分类</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="form-content">
      <el-form ref="form" :model="form" :rules="rules" label-width="126px">
        <el-form-item label="分类名称" prop="title">
          <el-input
            v-model="form.type_name"
            placeholder="请输入分类名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入路径"></el-input>
        </el-form-item>
        <el-form-item label="卖场" prop="market_id">
          <el-select
            v-model="form.market_id"
            clearable
            @change="selectMarket"
            filterable
            placeholder="请选择卖场"
          >
            <el-option
              v-for="item in marketList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ICON">
          <el-upload
            action="/api/client/base/uploadfile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            ref="upload"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="true"
            :limit="50"
            :headers="myHeaders"
            :file-list="fileList"
            accept="image/jpeg, image/jpg, image/gif, image/png"
            :multiple="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="排序">
          <el-col :span="5">
            <el-input
              v-model="form.sort"
              placeholder="数字越大越靠后"
            ></el-input>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-row>
            <el-button type="danger" @click="confirmAdd('form')"
              >立即保存</el-button
            >
            <el-button type="default" @click="cancel()">返回</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      validate: false,
      activeName: "first",
      articleTypes: [],
      form: {
        pid: 0,
        path: "",
        type_name: "",
        sort: 0,
        market_id: "",
      },
      rules: {
        type_name: [
          { required: true, message: "请输入分类标题", trigger: "blur" },
        ],
        market_id: [
          { required: true, message: "请选择卖场", trigger: "blur" },
        ],
      },
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      myHeaders: {
        "access-token": this.$store.state.token, //这里重新定义了请求头
        Authorization: this.$store.state.token,
        "user-id": this.$store.state.user_id,
      },
      marketList: [],//卖场列表
    };
  },
  mounted() {
    this.remoteMethod()
    this.loadArticleType();
  },
  methods: {
    // 获取卖场列表
    remoteMethod() {
      this.$http.post("/api/root/Market/marketList").then((res) => {
        console.log(res, "卖场列表");
        if (res.code == 1) {
          this.marketList = res.data ? res.data : [];
        }
      });
    },
    // 选择卖场
    selectMarket() {

    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
      console.log("file", file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file, fileList) {
      console.log("fileList", fileList);
      this.fileList = fileList;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    loadArticleType() {
      const id = this.$route.query.id;
      this.$http.get("/api/root/appCate/edit", { id: id }).then((rest) => {
        rest.data.typeInfo.cover.map((item) => {
          this.fileList.push({
            id: item.img_id,
            url: item.image_path,
          });
        });
        this.form = {
          ...rest.data.typeInfo,
        };
        this.articleTypes = rest.data.types;
      });
    },
    confirmAdd(form) {
      this.validateFormData(form);
      if (this.validate) {
        const _ths = this;
        if (this.fileList) {
          this.fileList.map((item) => {
            if (item.response) {
              _ths.form.cover = item.response.data.id;
            } else {
              _ths.form.cover = item.id;
            }
          });
        }
        this.$http
          .post("/api/root/appCate/edit", { ...this.form })
          .then((rest) => {
            if (rest.msg == "ok") {
              this.$message.success("修改成功");
              setTimeout(function () {
                _ths.$router.push({ name: "appCateList" });
              }, 800);
            } else {
              this.form = {
                ...this.form,
              };
              this.$message.error(rest.msg);
            }
          });
      }
    },
    cancel() {
      this.$router.push({ name: "appCateList" });
    },

    /**
     * 验证表单数据
     * @param form
     */
    validateFormData(form) {
      this.$refs[form].validate((valid) => {
        if (!valid) {
          this.$message({
            message: "表单数据未填写完整,操作失败！",
            type: "warning",
          });
          return false;
        }
        this.validate = true;
        return true;
      });
    },
    handleParentType(value) {
      this.form.pid = value;
      if (this.$refs.organizerUnit) {
        this.$refs.organizerUnit.dropDownVisible = false;
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import "index.less";
</style>